/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-09-29 20:27:29
 * Last Modified: 2017-08-01 15:21:40
 * File Name: account/account.go
 * Description:
 */
package account

import (
	"time"

	"qkleague/db"
	"qkleague/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/jsonq"

	rpc "qkleague/rpc/client/passport"

	log "github.com/cihub/seelog"
)

var (
	accountInstance *accountService

	userInfoData map[string]bool
)

type accountService struct {
}

func GetAccountService() *accountService {
	if accountInstance == nil {
		accountInstance = &accountService{}
	}
	return accountInstance
}

type QKLeague struct {
	Id        int64  `json:"id"`
	LeagueId  string `json:"league_id"`
	AccountId string `json:"account_id"`
	//PassWord        string `json:"pass_word"`
	NickName        string `json:"nick_name"`
	MainName        string `json:"main_name"`
	RegionAddr      string `json:"region_addr"`
	ContactPeer     string `json:"contact_peer"`
	Mobile          string `json:"mobile"`
	WashRoomNum     int    `json:"washroom_num"`
	WasherNum       int    `json:"washer_num"`
	BankAccountName string `json:"bank_account_name"`
	BankAccount     string `json:"bank_account"`
	Bank            string `json:"bank"`
	InsertTick      int64  `json:"insert_tick"` //插入时间
	UpdateTick      int64  `json:"update_tick"` //更新时间
	//PassWordChanged int    `json:"pass_word_changed"`
}

//用户在账号系统注册成功之后，在加盟商体系注册
func (p *accountService) Register(req *QKLeague) uint {
	if p.InsertUserInfo(req) == errorcode.EC_GL_SUCCESS {
		return errorcode.EC_GL_SUCCESS
	}
	if ok := rpc.Register(req.AccountId, req.AccountId[5:]); ok {
		return p.InsertUserInfo(req)
	}
	return errorcode.EC_ACCOUNT_USER_REGISTER_BY_PASSPORT_FAIL
}

func (p *accountService) InsertUserInfo(req *QKLeague) uint {
	tm := time.Now().Unix()
	if ui, err := rpc.QueryUserInfoByMobile(req.AccountId); err == nil { //从账号系统获取用户id
		dti := datatable.NewDataTableInsert()
		dti.SetTableName("league_user")
		dti.SetInsertValue("userid", ui.UserId)
		dti.SetInsertValue("account_id", req.AccountId)
		if req.NickName == "" {
			req.NickName = req.AccountId
		}
		dti.SetInsertValue("nick_name", req.NickName)
		dti.SetInsertValue("main_name", req.MainName)
		dti.SetInsertValue("region_addr", req.RegionAddr)
		if req.ContactPeer == "" {
			req.ContactPeer = req.NickName
		}
		dti.SetInsertValue("contact_peer", req.ContactPeer)
		if req.Mobile == "" {
			req.Mobile = req.AccountId
		}
		dti.SetInsertValue("mobile", req.Mobile)
		dti.SetInsertValue("bank_account_name", req.BankAccountName)
		dti.SetInsertValue("bank_account", req.BankAccount)
		dti.SetInsertValue("bank", req.Bank)
		dti.SetInsertValue("insert_tick", tm)
		dti.SetInsertValue("update_tick", tm)
		sql, values := dti.GenerateSQL()
		mysqlHelper := db.GetQKLeagueMySQLHelper()
		_, err := mysqlHelper.Exec(sql, values...)
		if err == nil {
			userInfoData[ui.UserId] = true
			return errorcode.EC_GL_SUCCESS
		} else {
			log.Warnf("InsertUserInfo, mysql err, err:%s", err.Error())
			return errorcode.EC_GL_INTERNAL_ERROR
		}
	} else {
		log.Errorf("accountService InsertUserInfo err. 查询用户信息失败. err:%s", err.Error())
	}
	return errorcode.EC_ACCOUNT_USER_NOT_REGISTER
}

//用户更新信息(除修改用户密码之外的操作)
func (p *accountService) UpdateUserInfo(uinfo map[string]interface{}) uint {
	jq := jsonq.NewQuery(uinfo)
	var userId string
	if val, err := jq.String("userid"); err == nil {
		userId = val
	} else {
		return errorcode.EC_USER_INFO_USER_ID_MISSING
	}

	dtu := datatable.NewDataTableUpdate()
	dtu.SetTableName("league_user")
	dtu.PushCondition("userid = ?", userId)

	if val, err := jq.String("main_name"); err == nil && val != "" {
		dtu.SetUpdateValue("main_name = ?", val)
	}
	if val, err := jq.String("nick_name"); err == nil && val != "" {
		dtu.SetUpdateValue("nick_name = ?", val)
	} /*
		if val, err := jq.String("account_id"); err == nil && val != "" {
			dtu.SetUpdateValue("account_id = ?", val)
		}*/
	if val, err := jq.String("region_addr"); err == nil && val != "" {
		dtu.SetUpdateValue("region_addr = ?", val)
	}
	if val, err := jq.String("contact_peer"); err == nil && val != "" {
		dtu.SetUpdateValue("contact_peer = ?", val)
	}

	if val, err := jq.String("mobile"); err == nil && val != "" {
		dtu.SetUpdateValue("mobile = ?", val)
	}

	if val, err := jq.String("bank_account_name"); err == nil && val != "" {
		dtu.SetUpdateValue("bank_account_name = ?", val)
	}
	if val, err := jq.String("bank_account"); err == nil && val != "" {
		dtu.SetUpdateValue("bank_account = ?", val)
	}
	if val, err := jq.String("bank"); err == nil && val != "" {
		dtu.SetUpdateValue("bank = ?", val)
	}
	if val, err := jq.Int("update_tick"); err == nil && val != 0 {
		dtu.SetUpdateValue("update_tick = ?", int64(val))
	} else if err != nil {
		dtu.SetUpdateValue("update_tick = ?", time.Now().Unix())
	}
	sql, values := dtu.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if _, err := mysqlHelper.Exec(sql, values...); err == nil {
		return errorcode.EC_GL_SUCCESS
	} else {
		log.Warnf("mysql err, :%s", err.Error())
	}
	return errorcode.EC_GL_INTERNAL_ERROR
}

func (p *accountService) DeleteUser(userId string) uint {
	if !userInfoData[userId] {
		return errorcode.EC_QKLEAGUE_USER_NOT_EXIST
	}
	sql := "delete from league_user where userid = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	_, err := mysqlHelper.Exec(sql, userId)
	if err == nil {
		delete(userInfoData, userId)
		return errorcode.EC_GL_SUCCESS
	}
	return errorcode.EC_GL_INTERNAL_ERROR
}

//判断账户是否存在
func (p *accountService) IsExistUser(userid string) bool {
	return userInfoData[userid]
}

//获取用户信息
func (p *accountService) GetUserInfoByUserid(userId string) *QKLeague {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("league_user")
	dtq.PushField(&datatable.FiledItem{Alias: "userid", Field: "userid"})
	dtq.PushField(&datatable.FiledItem{Alias: "account_id", Field: "account_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "nick_name", Field: "nick_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "main_name", Field: "main_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "region_addr", Field: "region_addr"})
	dtq.PushField(&datatable.FiledItem{Alias: "contact_peer", Field: "contact_peer"})
	dtq.PushField(&datatable.FiledItem{Alias: "mobile", Field: "mobile"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank_account_name", Field: "bank_account_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank_account", Field: "bank_account"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank", Field: "bank"})
	dtq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	dtq.PushCondition("userid = ?", userId)
	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql, values...); err == nil {
		if len(results) == 0 {
			return nil
		}
		for _, dt := range results {
			ui := &QKLeague{}
			ui.LeagueId = mysqlHelper.GetColString(dt, "userid")
			ui.AccountId = mysqlHelper.GetColString(dt, "account_id")
			ui.NickName = mysqlHelper.GetColString(dt, "nick_name")
			ui.MainName = mysqlHelper.GetColString(dt, "main_name")
			ui.RegionAddr = mysqlHelper.GetColString(dt, "region_addr")
			ui.ContactPeer = mysqlHelper.GetColString(dt, "contact_peer")
			ui.Mobile = mysqlHelper.GetColString(dt, "mobile")
			ui.BankAccountName = mysqlHelper.GetColString(dt, "bank_account_name")
			ui.BankAccount = mysqlHelper.GetColString(dt, "bank_account")
			ui.Bank = mysqlHelper.GetColString(dt, "bank")
			ui.InsertTick = int64(mysqlHelper.GetColInt(dt, "insert_tick"))
			ui.UpdateTick = int64(mysqlHelper.GetColInt(dt, "update_tick"))
			return ui
		}
	} else {
		log.Warnf("mysql err, %s", err.Error())
	}
	return nil
}

func init() {
	userInfoData = make(map[string]bool)

	loadUserInfoData()
}

func loadUserInfoData() {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("league_user")
	dtq.PushField(&datatable.FiledItem{Alias: "userid", Field: "userid"})
	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql, values...); err == nil {
		if len(results) == 0 {
			return
		}
		for _, dt := range results {
			userId := mysqlHelper.GetColString(dt, "userid")
			userInfoData[userId] = true
		}
	} else {
		log.Warnf("mysql err, %s", err.Error())
	}
}
